package com.kevin.netty.server.basic;

import com.kevin.netty.starter.util.ChannelGroupHelper;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public abstract class AbstractInboundHandler extends SimpleChannelInboundHandler<Object> {

    @Resource
    private ChannelGroupHelper channelGroupHelper;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        channelGroupHelper.add(ctx.channel());
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        channelGroupHelper.unregister(ctx.channel());
        super.channelInactive(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.warn(">>>>>> 链接：{} 已断开，异常信息：{} >>>>>>", ctx.channel().id().asShortText(), cause.getMessage());
        channelGroupHelper.unregister(ctx.channel());
        super.exceptionCaught(ctx, cause);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
        Channel channel = ctx.channel();
        if (evt instanceof IdleStateEvent) {
            IdleState state = ((IdleStateEvent) evt).state();
            if (state == IdleState.READER_IDLE) {
                log.warn(">>>>>> 空闲链接：{} 已断开 >>>>>>", ctx.channel().id().asShortText());
                channelGroupHelper.unregister(channel);
            }
        }
    }

}
